package com.nleaves.baiduloc.activity;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.Poi;
import com.baidu.mapapi.search.core.CityInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.poi.*;
import com.baidu.mapapi.search.sug.OnGetSuggestionResultListener;
import com.baidu.mapapi.search.sug.SuggestionResult;
import com.baidu.mapapi.search.sug.SuggestionSearch;
import com.baidu.mapapi.search.sug.SuggestionSearchOption;
import com.nleaves.baiduloc.citylist.adapter.CityAdapter;
import com.nleaves.baiduloc.citylist.data.CityData;
import com.nleaves.baiduloc.citylist.model.CityItem;
import com.nleaves.baiduloc.citylist.widget.ContactItemInterface;
import com.nleaves.baiduloc.citylist.widget.ContactListViewImpl;
import com.nleaves.baiduloc.service.LocationService;

import java.util.ArrayList;
import java.util.List;

/***
 * 单点定位示例，用来展示基本的定位结果，配置在LocationService.java中
 * 默认配置也可以在LocationService中修改
 * 默认配置的内容自于开发者论坛中对开发者长期提出的疑问内容
 *
 * @author baidu
 */
public class LocationActivity extends BaseActivity implements OnClickListener, TextWatcher, OnGetPoiSearchResultListener, OnGetSuggestionResultListener {
    private LocationService locationService;
    private TextView LocationResult;
    //    private Button startLocation;
    private ImageView back;
    private ImageView fresh;
    //    private TextView textview;
    private EditText searchAddress;
    private EditText searchCity;
    private TextView load;
    private LinearLayout layout1;
    private LinearLayout layout2;
    private LinearLayout layout3;
    private String cityValue;
    private String city;
    private TextView curLocCity;
    private SearchView searchBox;
    private Context context_ = LocationActivity.this;
    private ContactListViewImpl citylist;
    private String searchString;
    private Object searchLock = new Object();
    boolean inSearchMode = false;
    private Editable s;
    private final static String TAG = "MainActivity2";
    List<ContactItemInterface> contactList;
    List<ContactItemInterface> filterList;
    private SearchListTask curSearchTask = null;
    private boolean flag = false;
    private String city_item;
    private PoiSearch mPoiSearch = null;
    private SuggestionSearch mSuggestionSearch = null;

//    private BaiduMap mBaiduMap = null;
    /**
     * 搜索关键字输入窗口
     */

    private AutoCompleteTextView keyWorldsView = null;

    private ArrayAdapter<String> sugAdapter = null;
//    private AddressAdapter addressAdapter = null;

    private int load_Index = 0;
    private List<ContactItemInterface> searchList;
//    private Button search;
//    private ArrayList<String> arrayList;

    private void initViews() {
//        textview = (TextView) findViewById(R.id.textview);
        load = (TextView) findViewById(R.id.load);
        fresh = (ImageView) findViewById(R.id.fresh);
        searchAddress = (EditText) findViewById(R.id.search_address);
        searchCity = (EditText) findViewById(R.id.search_city);
        searchCity.addTextChangedListener(this);

//        searchAddress.addTextChangedListener(this);
//        searchCity.setQueryHint("请输入城市");

        back = (ImageView) findViewById(R.id.back);
        back.setOnClickListener(this);
        layout1 = (LinearLayout) findViewById(R.id.layout1);
        layout2 = (LinearLayout) findViewById(R.id.layout2);
        layout3 = (LinearLayout) findViewById(R.id.layout3);

        LocationResult = (TextView) findViewById(R.id.LocationResult);
        LocationResult.setOnClickListener(this);
        fresh.setOnClickListener(this);

//        search = (Button) findViewById(R.id.search);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        // -----------demo view config ------------
        setContentView(R.layout.activity_location);
        initViews();

//        CityData.JsonXml();

//        arrayList = new ArrayList<>();

        flag = false;

        LocationResult.setMovementMethod(ScrollingMovementMethod.getInstance());
//        startLocation = (Button) findViewById(R.id.addfence);

        curLocCity = (TextView) findViewById(R.id.curLocCity);

        filterList = new ArrayList<ContactItemInterface>();
        contactList = CityData.getSampleContactList();

        CityAdapter adapter = new CityAdapter(this, R.layout.city_item, contactList);

        citylist = (ContactListViewImpl) this.findViewById(R.id.cityList);
        citylist.setFastScrollEnabled(true);
        citylist.setAdapter(adapter);

        citylist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView parent, View v, int position,
                                    long id) {
                searchList = inSearchMode ? filterList
                        : contactList;

//                Toast.makeText(context_,
//                        searchList.get(position).getDisplayInfo(),
//                        Toast.LENGTH_SHORT).show();

                city_item = searchList.get(position).getDisplayInfo();

                layout1.setVisibility(View.VISIBLE);
                layout2.setVisibility(View.GONE);
                searchCity.setVisibility(View.GONE);
                searchAddress.setVisibility(View.VISIBLE);

                flag = true;
                searchCity.setText("");
//                LocationResult.setText(city_item + "市");
            }
        });

//        searchBox = (SearchView) findViewById(R.id.search);
//        searchBox.setOnQueryTextListener(this);

        // 初始化搜索模块，注册搜索事件监听
        mPoiSearch = PoiSearch.newInstance();
        mPoiSearch.setOnGetPoiSearchResultListener(this);
        mSuggestionSearch = SuggestionSearch.newInstance();
        mSuggestionSearch.setOnGetSuggestionResultListener(this);
        keyWorldsView = (AutoCompleteTextView) findViewById(R.id.search_address);

        sugAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_dropdown_item_1line);
        keyWorldsView.setAdapter(sugAdapter);


//        addressAdapter = new AddressAdapter(this,R.layout.address_list);
//        keyWorldsView.setAdapter(addressAdapter);

//        mBaiduMap = ((SupportMapFragment) (getSupportFragmentManager()
//                .findFragmentById(R.id.map))).getBaiduMap();

        /**
         * 当输入关键字变化时，动态更新建议列表
         */
        keyWorldsView.addTextChangedListener(new TextWatcher()
        {

            @Override
            public void afterTextChanged(Editable arg0)
            {
            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                                          int arg2, int arg3)
            {

            }

            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2,
                                      int arg3)
            {
                if (cs.length() <= 0)
                {
                    return;
                }
                else
                {
//                    search.setVisibility(View.GONE);
                }
                String city = ((TextView) findViewById(R.id.LocationResult)).getText()
                        .toString();
                /**
                 * 使用建议搜索服务获取建议列表，结果在onSuggestionResult()中更新
                 */
                mSuggestionSearch
                        .requestSuggestion((new SuggestionSearchOption())
                                .keyword(cs.toString()).city(city));

            }
        });
//        int[] location = new int[2];
//        keyWorldsView.getLocationInWindow(location);
//        int x = location[0];
//        int y = location[1];
        keyWorldsView.setDropDownWidth(getWindowManager().getDefaultDisplay().getWidth()+50);
        keyWorldsView.setDropDownVerticalOffset(0);
        keyWorldsView.setDropDownHorizontalOffset(-10);
//        keyWorldsView.setCompoundDrawablePadding();

    }

    @Override
    protected void onDestroy() {
        mPoiSearch.destroy();
        mSuggestionSearch.destroy();
        super.onDestroy();
    }

    /**
     * 影响搜索按钮点击事件
     *
     * @param v
     */
    public void searchButtonProcess(View v) {
//        EditText editCity = (EditText) findViewById(R.id.city);
//        EditText editSearchKey = (EditText) findViewById(R.id.search_address);
//        mPoiSearch.searchInCity((new PoiCitySearchOption())
//                .city(editCity.getText().toString())
//                .keyword(editSearchKey.getText().toString())
//                .pageNum(load_Index));

        TextView textView = (TextView) findViewById(R.id.LocationResult);
        EditText editSearchKey = (EditText) findViewById(R.id.search_address);
        mPoiSearch.searchInCity((new PoiCitySearchOption())
                .city(textView.getText().toString())
                .keyword(editSearchKey.getText().toString())
                .pageNum(load_Index));

        Toast.makeText(this, editSearchKey.getText().toString(), Toast.LENGTH_SHORT).show();
    }

//    public void goToNextPage(View v) {
//        load_Index++;
//        searchButtonProcess(null);
//    }

    public void onGetPoiResult(PoiResult result) {
        if (result == null
                || result.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
            Toast.makeText(LocationActivity.this, "未找到结果", Toast.LENGTH_LONG)
                    .show();
            return;
        }
//        if (result.error == SearchResult.ERRORNO.NO_ERROR) {
//            mBaiduMap.clear();
//            PoiOverlay overlay = new MyPoiOverlay(mBaiduMap);
//            mBaiduMap.setOnMarkerClickListener(overlay);
//            overlay.setData(result);
//            overlay.addToMap();
//            overlay.zoomToSpan();
//            return;
//        }
        if (result.error == SearchResult.ERRORNO.AMBIGUOUS_KEYWORD) {

            // 当输入关键字在本市没有找到，但在其他城市找到时，返回包含该关键字信息的城市列表
            String strInfo = "在";
            for (CityInfo cityInfo : result.getSuggestCityList()) {
                strInfo += cityInfo.city;
                strInfo += ",";
            }
            strInfo += "找到结果";
            Toast.makeText(LocationActivity.this, strInfo, Toast.LENGTH_LONG)
                    .show();
        }
    }

    public void onGetPoiDetailResult(PoiDetailResult result) {
        if (result.error != SearchResult.ERRORNO.NO_ERROR) {
            Toast.makeText(LocationActivity.this, "抱歉，未找到结果", Toast.LENGTH_SHORT)
                    .show();
        } else {
            Toast.makeText(LocationActivity.this, result.getName() + ": " + result.getAddress(), Toast.LENGTH_SHORT)
                    .show();
        }
    }

    @Override
    public void onGetSuggestionResult(SuggestionResult res) {
        if (res == null || res.getAllSuggestions() == null) {
            return;
        }

        sugAdapter.clear();
        for (SuggestionResult.SuggestionInfo info : res.getAllSuggestions()) {
            if (info.key != null)
                sugAdapter.add(info.key);
        }
        sugAdapter.notifyDataSetChanged();

//        addressAdapter.clear();
//        for (SuggestionResult.SuggestionInfo info : res.getAllSuggestions()) {
//            if (info.key != null)
//                addressAdapter.add(info.key);
//        }
//        addressAdapter.notifyDataSetChanged();


        List<SuggestionResult.SuggestionInfo> list = res.getAllSuggestions();
        for (SuggestionResult.SuggestionInfo info : list) {
//            Log.d("dadada", info.city + "..........");
//            Log.d("dadada", info.uid +",,,,,,,,");
//            Log.d("dadada", info.pt + "\\\\\\\\\\");
//            Log.d("dadada", info.district +"[[[[[[[[[[[");
            Log.d("dadada", info.key + "^^^^^^^^^^.");
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        searchString = searchCity.getText().toString().trim().toUpperCase();
//        searchString = newText.trim().toUpperCase();
        this.s = s;
        if (curSearchTask != null
                && curSearchTask.getStatus() != AsyncTask.Status.FINISHED) {
            try {
                curSearchTask.cancel(true);
            } catch (Exception e) {
                Log.i(TAG, "Fail to cancel running search task");
            }
        }
        curSearchTask = new SearchListTask();
        curSearchTask.execute(searchString);
    }

    private class SearchListTask extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... params) {
            filterList.clear();

            String keyword = params[0];

            inSearchMode = (keyword.length() > 0);

            if (inSearchMode) {
                // get all the items matching this
                for (ContactItemInterface item : contactList) {
                    CityItem contact = (CityItem) item;

                    boolean isPinyin = contact.getFullName().toUpperCase().indexOf(keyword) > -1;
                    boolean isChinese = contact.getNickName().indexOf(keyword) > -1;

                    if (isPinyin || isChinese) {
                        filterList.add(item);
                    }
                }
            }
            return null;
        }

        protected void onPostExecute(String result) {

            synchronized (searchLock) {

                int length = s.toString().length();
                int visibility = layout3.getVisibility();
                if (filterList.size() > 0) {
                    if (visibility == View.VISIBLE && length > 0) {
                        layout3.setVisibility(View.GONE);
                    } else if (visibility == View.GONE && length == 0) {
                        layout3.setVisibility(View.VISIBLE);
                    }
                } else {
                    layout3.setVisibility(View.VISIBLE);
                }

                if (inSearchMode) {
                    CityAdapter adapter = new CityAdapter(context_, R.layout.city_item, filterList);
                    adapter.setInSearchMode(true);
                    citylist.setInSearchMode(true);
                    citylist.setAdapter(adapter);
                } else {
                    CityAdapter adapter = new CityAdapter(context_, R.layout.city_item, contactList);
                    adapter.setInSearchMode(false);
                    citylist.setInSearchMode(false);
                    citylist.setAdapter(adapter);
                }
            }
        }
    }

    /**
     * 显示请求字符串
     *
     * @param str
     */
    public void logMsg(String str) {
        try {
            if (LocationResult != null)
                LocationResult.setText(str);
//            Toast.makeText(this, str, Toast.LENGTH_SHORT).show();
            String[] ss = str.split("\n");
            for (String s : ss) {
                if (s.contains("city") && !s.contains("code")) {
                    String[] list = s.split(":");
                    city = list[1];
                    System.out.print(city);
//                    Toast.makeText(this, value, Toast.LENGTH_SHORT).show();

                    if (!flag) {
                        LocationResult.setText(city);
                    } else {
                        LocationResult.setText(city_item);
                    }
                    //当前定位城市
                    curLocCity.setText(city);

//                    String city_name = getIntent().getStringExtra("city");
//                    LocationResult.setText(city_name+"市");
                } else if (s.contains("Poi")) {
                    String[] list = s.split(":");
                    String st = list[1];
                    String[] string = st.split(";");
                    cityValue = string[1];
                    load.setText(cityValue);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /***
     * Stop location service
     */
    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        locationService.unregisterListener(mListener); //注销掉监听
        locationService.stop(); //停止定位服务
        super.onStop();
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        // -----------location config ------------
        locationService = ((LocationApplication) getApplication()).locationService;
        //获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的
        locationService.registerListener(mListener);
        //注册监听
        int type = getIntent().getIntExtra("from", 0);
        if (type == 0) {
            locationService.setLocationOption(locationService.getDefaultLocationClientOption());
        } else if (type == 1) {
            locationService.setLocationOption(locationService.getOption());
        }
//        startLocation.setOnClickListener(new OnClickListener() {
//
//            @Override
//            public void onClick(View v) {
//                if (startLocation.getText().toString().equals(getString(R.string.startlocation))) {
        locationService.start();// 定位SDK
//                    // start之后会默认发起一次定位请求，开发者无须判断isstart并主动调用request
//                    startLocation.setText(getString(R.string.stoplocation));
//                } else {
//                    locationService.stop();
//                    startLocation.setText(getString(R.string.startlocation));
//                }
//            }
//        });
    }


    /*****
     * @see copy funtion to you project
     * 定位结果回调，重写onReceiveLocation方法，可以直接拷贝如下代码到自己工程中修改
     */
    private BDLocationListener mListener = new BDLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // TODO Auto-generated method stub

//            if (null != location && location.getLocType() == BDLocation.TypeServerError) {

            if (null != location && location.getLocType() != BDLocation.TypeServerError) {

//            if(null == location) {
//                return;
//            }else{

                StringBuffer sb = new StringBuffer(256);
                sb.append("time : ");
                /**
                 * 时间也可以使用systemClock.elapsedRealtime()方法 获取的是自从开机以来，每次回调的时间；
                 * location.getTime() 是指服务端出本次结果的时间，如果位置不发生变化，则时间不变
                 */

                sb.append(location.getTime());
                sb.append("\nerror code : ");
                sb.append(location.getLocType());
                sb.append("\nlatitude : ");
                sb.append(location.getLatitude());
                sb.append("\nlontitude : ");
                sb.append(location.getLongitude());
                sb.append("\nradius : ");
                sb.append(location.getRadius());
                sb.append("\nCountryCode : ");
                sb.append(location.getCountryCode());
                sb.append("\nCountry : ");
                sb.append(location.getCountry());
                sb.append("\ncitycode : ");
                sb.append(location.getCityCode());
                sb.append("\ncity : ");
                sb.append(location.getCity());
                sb.append("\nDistrict : ");
                sb.append(location.getDistrict());
                sb.append("\nStreet : ");
                sb.append(location.getStreet());
                sb.append("\naddr : ");
                sb.append(location.getAddrStr());
                sb.append("\nDescribe: ");
                sb.append(location.getLocationDescribe());
                sb.append("\nDirection(not all devices have value): ");
                sb.append(location.getDirection());
                sb.append("\nPoi: ");

                if (location.getPoiList() != null && !location.getPoiList().isEmpty()) {
                    for (int i = 0; i < location.getPoiList().size(); i++) {
                        Poi poi = (Poi) location.getPoiList().get(i);
                        sb.append(poi.getName() + ";");
                    }
                }
                if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
                    sb.append("\nspeed : ");
                    sb.append(location.getSpeed());// 单位：km/h
                    sb.append("\nsatellite : ");
                    sb.append(location.getSatelliteNumber());
                    sb.append("\nheight : ");
                    sb.append(location.getAltitude());// 单位：米
                    sb.append("\ndescribe : ");
                    sb.append("gps定位成功");
                } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                    // 运营商信息
                    sb.append("\noperationers : ");
                    sb.append(location.getOperators());
                    sb.append("\ndescribe : ");
                    sb.append("网络定位成功");
                } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
                    sb.append("\ndescribe : ");
                    sb.append("离线定位成功，离线定位结果也是有效的");
                } else if (location.getLocType() == BDLocation.TypeServerError) {
                    sb.append("\ndescribe : ");
                    sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
                } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                    sb.append("\ndescribe : ");
                    sb.append("网络不同导致定位失败，请检查网络是否通畅");
                } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                    sb.append("\ndescribe : ");
                    sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
                }
                logMsg(sb.toString());
            }
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.LocationResult:
//                Toast.makeText(this, "hh", Toast.LENGTH_SHORT).show();
//                setContentView(R.layout.search_city);

                if (layout1.getVisibility() == View.VISIBLE) {
                    layout1.setVisibility(View.GONE);
                    layout2.setVisibility(View.VISIBLE);
                    searchCity.setVisibility(View.VISIBLE);
                    searchAddress.setVisibility(View.GONE);
//                    search.setVisibility(View.INVISIBLE);
                } else {
                    layout1.setVisibility(View.VISIBLE);
                    layout2.setVisibility(View.GONE);
                    searchCity.setVisibility(View.GONE);
                    searchAddress.setVisibility(View.VISIBLE);
//                    search.setVisibility(View.VISIBLE);
//                    curLocCity.setText(city);
                }

//                Intent intent = new Intent(LocationActivity.this, CityActivity.class);
//                intent.putExtra("city", city);
//                startActivity(intent);
                break;
            case R.id.fresh:
                Toast.makeText(this, "重新定位当前位置", Toast.LENGTH_SHORT).show();
                //重新定位当前位置
                locationService.start();
                break;
            default:
                break;
        }
    }

    //Px转dp
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
    //testBranch
}